<template>
  <span>
    <slot v-if="!closed">
      {{day}}
      <span class="sub">天</span>
      {{hour}}
      <span class="sub">时</span>
      {{min}}
      <span class="sub">分</span>
      {{sec}}
      <span class="sub">秒</span>
    </slot>
    <slot v-else>
      <span class="end">{{endTime}}</span>
    </slot>
  </span>
</template>
<script>
export default {
  data() {
    return {
      closed: false,
      day: "",
      hour: "",
      min: "",
      sec: ""
    };
  },
  props: {
    startTime: {
      type: String,
      default: ""
    },
    endTime: {
      type: String,
      default: ""
    }
  },
  mounted() {
    this.countdowm(this.startTime, this.endTime);
  },
  methods: {
    countdowm(start, end) {
      let self = this;
      let timer = setInterval(function() {
        self.closed = false;
        let nowTime = new Date();
        let endTime = Date.parse(new Date(end.replace(/-/g, "/")));
        let startTime = Date.parse(new Date(start.replace(/-/g, "/")));
        let e = endTime - nowTime.getTime();
        let s = startTime - nowTime.getTime();
        if (s > 0) {
          //未开始
          self.calDate(s);
          self.$emit("status", 0);
        } else if (e > 0) {
          // 未结束
          self.calDate(e);
          self.$emit("status", 1);
        } else {
          //已结束
            clearInterval(timer);
            self.closed = true;
            self.$emit("status", 2);
        }
      }, 1000);
    },
    calDate(time) {
      let day = Math.floor(time / 86400000);
      let hour = Math.floor((time / 3600000) % 24);
      let min = Math.floor((time / 60000) % 60);
      let sec = Math.floor((time / 1000) % 60);
      hour = hour < 10 ? "0" + hour : hour;
      min = min < 10 ? "0" + min : min;
      sec = sec < 10 ? "0" + sec : sec;
      this.day = day;
      this.hour = hour;
      this.min = min;
      this.sec = sec;
    }
  }
};
</script>

<style lang="scss" scoped>
span {
  font-size: 28px;
  color: #c0392b;
  font-weight: bold;

  .sub {
    font-weight: normal;
    color: #808695;
    font-size: small;
  }

  .end {
    font-size: 20px;
    color: #6a6e79;
  }
}
</style>